#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../Includes/Color.h"
#include "../Includes/Matrix.h"
#include "../Includes/Rectangle.h"
#include "../Includes/Surface.h"
#include <png.h>

/// <summary>
/// TODO
/// </summary>
int GalSaveSurface(SurfacePtr surface, const char *file)
{
	int i = 0;
	FILE *handle;
	if (!(handle = fopen(file, "wb")))
		return -1;

	png_structp png_ptr;
	if (!(png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)))
		return -2;

	png_infop info_ptr;
	if (!(info_ptr = png_create_info_struct(png_ptr)))
		return -2;

	if (setjmp(png_jmpbuf(png_ptr)))
		return -3;

	png_init_io(png_ptr, handle);

	if (setjmp(png_jmpbuf(png_ptr)))
		return -3;

	int width = surface->width;
	int height = surface->height;
	int bit_depth = 8;

	png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
		PNG_COLOR_TYPE_RGBA,
		PNG_INTERLACE_NONE,
		PNG_COMPRESSION_TYPE_BASE,
		PNG_FILTER_TYPE_BASE);

	png_write_info(png_ptr, info_ptr);

	png_bytep data;
	if (!(data = (png_bytep)surface->data))
		return -3;

	for (i = 0; i < height; i++) {
		png_write_row(png_ptr, data);
		data += surface->stride;
	}

	png_write_end(png_ptr, NULL);

	png_write_destroy(png_ptr);

	fclose(handle);

	return 0;
}
